package com.site.blog.my.core.controller.admin;

import com.site.blog.my.core.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

@Controller
@RequestMapping("/admin")
public class UploadController {

    private final static String filePath = "/upload/";


    @PostMapping({"/upload/file"})
    @ResponseBody
    public Result upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) throws URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称通用方法
        String newFileName = UUID.UU32() + suffixName;
        //创建文件
        String path = BlogUtils.getUploadFilePath() + filePath + BlogUtils.prefix();
        File fielPath = new File(path);
        File destFile = new File(path + newFileName);
        try {
            if (!fielPath.exists()) {
                if (!fielPath.mkdirs()) {
                    throw new IOException("文件夹创建失败,路径为：" + fielPath);
                }
            }
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Result result = ResultGenerator.genSuccessResult();
        // result.setData(MyBlogUtils.getHost(new URI(httpServletRequest.getRequestURL() + "")) + filePath + BlogUtils.prefix() + newFileName);
        result.setData(filePath + BlogUtils.prefix() + newFileName);
        return result;
    }

}
